package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.swing.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishContorller {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        //清除所有的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<Dish>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //构造条件查询构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        /*//添加是否被删除条件
        wrapper.eq(Dish::getIsDeleted,0);*/
        //添加过滤条件
        wrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        wrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo, wrapper);


        //因为需要展示菜品分类名称，但Dish类中没有菜品分类名称的字段，所以需要使用DishDto展示
        //对象拷贝----records的泛型是dish，需要重新处理
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        //处理records
        List<Dish> records = pageInfo.getRecords();
        //遍历每条record
        List<DishDto> list = records.stream().map((item) -> {
            //创建DishDto对象
            DishDto dishDto = new DishDto();
            //对象拷贝将item（dish）中的数据拷贝到disDto中
            BeanUtils.copyProperties(item, dishDto);

            //针对每条record（item）获取对应的菜品分类id。（ 菜品表中含有菜品分类id---作为外键关联分类表）
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                //获得对应的分类名称
                String categoryName = category.getName();
                //给disDto添加分类名称
                dishDto.setCategoryName(categoryName);
            }
            //返回此次disDto
            return dishDto;
        }).collect(Collectors.toList());
        //对新的records进行赋值
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品基本信息和口味信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id){
        log.info("查询id为{}",id);

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清除所有的缓存
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        //清除单个分类下的菜品缓存信息
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }

    /**
     * 停售/起售菜品
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("状态修改为：{}",status);
        log.info("操作id为：{}",ids);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId,ids);
        List<Dish> dishList = dishService.list(wrapper);

/*        dishList = dishList.stream().map((item) -> {
            item.setStatus(status);
            return item;
        }).collect(Collectors.toList());*/

        for (Dish dish : dishList) {
            dish.setStatus(status);
        }
        dishService.updateBatchById(dishList);
        /*for (Long item : ids) {
            Dish dish = dishService.getById(item);
            dish.setStatus(status);
            dishService.updateById(dish);
        }*/

        //清除所有的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("删除id为：{}的菜品",ids);
        dishService.removeWithFlavor(ids);
/*        for (Long item : ids) {
            Dish dish = dishService.getById(item);
            dish.setIsDeleted(1);
            dishService.updateById(dish);
        }*/

        //清除所有的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("删除成功");
    }

    /**
     * 根据分类id查询菜品
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        String key = "dish_" +dish.getCategoryId() + "_" + dish.getStatus();
        List<DishDto> dishDtoList = null;

        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //如果存在，直接返回，无需查询数据库
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        log.info("查询的菜品为：{}",dish);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //查询菜品状态是否为1（起售）
        wrapper.eq(Dish::getStatus,1);
        //添加排序条件，sort升序排，更新时间降序排
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(wrapper);

        dishDtoList = dishList.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            //将菜品基本信息复制到dishDto
            BeanUtils.copyProperties(item,dishDto);
            //查询每个菜品的口味信息并赋值
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> list = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(list);

            //获取分类名称信息
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                //获得对应的分类名称
                String categoryName = category.getName();
                //给disDto添加分类名称
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}

